//
//  AppDelegate+CheckVersionFromAppStore.m
//  mcrmSAAS
//
//  Created by yuxiuyi on 16/8/11.
//  Copyright © 2016年 GuangZhouXuanWu. All rights reserved.
//

#import "AppDelegate+CheckVersionFromAppStore.h"

@implementation AppDelegate (CheckVersionFromAppStore)

- (void)chectVersionFromAppStore
{
    //TODO AppStore
    return;
    
    NSString *urlStr = [[NSString alloc]initWithFormat:@"http://itunes.apple.com/lookup?id=1035198283"];
    
    NSURL *url = [[NSURL alloc]initWithString:urlStr];
    
    NSMutableURLRequest *RequestPost = [NSMutableURLRequest requestWithURL:url];
    
    [RequestPost setHTTPMethod:@"POST"];
    
    NSData *data = [NSURLConnection sendSynchronousRequest:RequestPost returningResponse:nil error:nil];
    
    NSDictionary *versionData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *results = [versionData objectForKey:@"results"];
    NSString *version = [[results firstObject] objectForKey:@"version"];
    NSString *trackViewUrl = [[results firstObject] objectForKey:@"trackViewUrl"];
    
    BOOL isUpdata = [self compareServerVersion:version withLocalVersion:[XLGContext context].m_szVersionname];
    
    if (isUpdata == YES)
    {
        [XUIAlertView alertViewWithTitle:@"提示" message:@"AppStore上发现新版本，是否更新？" cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
        {
            if (nClickindex == 1)
            {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:trackViewUrl]];
            }
        }];
    }
}

- (BOOL)compareServerVersion:(NSString*)serverVersion withLocalVersion:(NSString*)localVersion
{
    BOOL updata = NO;
    if (serverVersion ==nil || [serverVersion isEqualToString:@""])
    {
        NSLog(@"Server version is empty.");
        return updata;
    }
    if (localVersion ==nil || [localVersion isEqualToString:@""])
    {
        NSLog(@"Local version is empty.");
        return updata;
    }
    
    NSArray *serComps = [serverVersion componentsSeparatedByString:@"."];
    NSArray *locComps = [localVersion componentsSeparatedByString:@"."];
    for (int index =0; index < serComps.count; index++)
    {
        NSUInteger numServer = [[serComps objectAtIndex:index] integerValue];
        NSUInteger numLocal = 0;
        
        if (locComps.count > index)
            numLocal = [[locComps objectAtIndex:index] integerValue];

        if (numServer > numLocal)
        {
            updata = YES;
            break;
        }
    }
    return updata;
}

@end
